<template>
  <div class="solution-statistics">
    <el-card class="time-selector">
      <el-radio-group v-model="timeRange" @change="fetchData">
        <el-radio-button label="7">近7天</el-radio-button>
        <el-radio-button label="15">近15天</el-radio-button>
        <el-radio-button label="30">近30天</el-radio-button>
      </el-radio-group>
    </el-card>
    
    <el-row :gutter="20" class="chart-container">
      <el-col :span="12">
        <el-card>
          <div ref="lineChart" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div ref="pieChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';

const timeRange = ref('7');
const lineChart = ref(null);
const pieChart = ref(null);

const loading = ref(false);
const error = ref(null);

const fetchData = async () => {
  try {
    loading.value = true;
    error.value = null;
    
    const [statsRes, difficultyRes] = await Promise.all([
      getSolutionStatisticsService(timeRange.value),
      getSolutionDifficultyStatsService(timeRange.value)
    ]);
    
    const lineData = {
      dates: statsRes.data.dates,
      total: statsRes.data.total,
      new: statsRes.data.new
    };
    
    initLineChart(lineData);
    initPieChart(difficultyRes.data);
  } catch (err) {
    error.value = err;
    console.error('获取统计数据失败:', err);
  } finally {
    loading.value = false;
  }
};

const initLineChart = (data) => {
  const chart = echarts.init(lineChart.value);
  chart.setOption({
    title: { text: '题解数量趋势' },
    tooltip: { trigger: 'axis' },
    legend: { data: ['总题解', '新增题解'] },
    xAxis: { type: 'category', data: data.dates },
    yAxis: { type: 'value' },
    series: [
      { name: '总题解', type: 'line', data: data.total },
      { name: '新增题解', type: 'line', data: data.new }
    ]
  });
};

const initPieChart = (data) => {
  const chart = echarts.init(pieChart.value);
  chart.setOption({
    title: { text: '题目难度分布' },
    tooltip: { trigger: 'item' },
    legend: { orient: 'vertical', right: 10, top: 'center' },
    series: [
      {
        name: '难度分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
        label: { show: true, formatter: '{b}: {c} ({d}%)' },
        emphasis: { label: { show: true, fontSize: '18', fontWeight: 'bold' } },
        data: data
      }
    ]
  });
};

onMounted(() => {
  fetchData();
  window.addEventListener('resize', () => {
    echarts.getInstanceByDom(lineChart.value)?.resize();
    echarts.getInstanceByDom(pieChart.value)?.resize();
  });
});
</script>

<style scoped>
.solution-statistics {
  padding: 20px;
}
.time-selector {
  margin-bottom: 20px;
}
.chart-container {
  margin-top: 20px;
}
.chart {
  width: 100%;
  height: 400px;
}
</style>